package com.bdc.whatwhat.views;

import android.content.Context;
import android.os.AsyncTask;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bdc.whatwhat.Constantes;
import com.bdc.whatwhat.R;
import com.bdc.whatwhat.activities.MainActivity;
import com.bdc.whatwhat.adapters.ObjectAdapter;
import com.bdc.whatwhat.adapters.WhatWhatFluxAdapter;
import com.bdc.whatwhat.factory.Factory;
import com.bdc.whatwhat.modele.WhatWhat;
import com.bdc.whatwhat.modele.Whatter;
import com.bdc.whatwhat.session.SessionManager;
import com.bdc.whatwhat.task.FaireWhatWhatTask;
import com.bdc.whatwhat.task.FluxTask;
import com.bdc.whatwhat.task.RechercheTask;
import com.bdc.whatwhat.views.cell.WhatWhatCell;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by gfimac on 18/07/2014.
 */
public class SaisieWhatWhat extends RelativeLayout implements TextWatcher, RechercheTask.RechercheTaskDelegate, ObjectAdapter.ObjectAdapterLoadMore, View.OnClickListener, FluxTask.FluxTaskDelegate, FaireWhatWhatTask.FaireWhatWhatTaskDelegate {

    ListView listView;
    EditText editText;
    TextView saisie_edit_nombre_caracteres;
    Circle circle;

    ObjectAdapter<WhatWhat> adapter;

    List<WhatWhat> whatWhatList = new ArrayList<WhatWhat>();
    AsyncTask task;

    SessionManager session;

    String text = "";
    int page = 1;
    boolean loadmore = true;

    FaireWhatWhatTask faireWhatWhatTask;

    public SaisieWhatWhat(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SaisieWhatWhat(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();

        session = new SessionManager(getContext());

        charger();
        remplir();
        ajouterListeners();

        if(!isInEditMode())
            onTextChanged("",0,0,0);
    }

    public void charger(){
        listView = (ListView) findViewById(R.id.saisie_list_whatwhat);
        editText = (EditText) findViewById(R.id.saisie_edit_text);
        saisie_edit_nombre_caracteres = (TextView) findViewById(R.id.saisie_edit_nombre_caracteres);
    }

    public void remplir(){
        adapter = new ObjectAdapter<WhatWhat>(getContext(),whatWhatList,R.layout.cell_whatwhat, WhatWhatCell.class, this);
        listView.setAdapter(adapter);
        editText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(Constantes.tailleWhatWhat)});
    }

    private void ajouterListeners() {
        editText.addTextChangedListener(this);
        //adapter.listener = this;
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i2, int count) {
        text = charSequence.toString();
        page = 1;
        loadmore = true;

        saisie_edit_nombre_caracteres.setText((Constantes.tailleWhatWhat-text.length())+"");

        if(task != null)
            task.cancel(true);

        if(text == null || text.length() == 0){
            task = new FluxTask(this);
            task.execute(page,session.getToken());
        }else{
            task = new RechercheTask(this);
            task.execute(text, page,session.getToken());
        }

    }

    @Override
    public void afterTextChanged(Editable editable) {

    }

    @Override
    public void loadMore() {
        if( loadmore ) {
            page += 1;
            if(task != null) {
                task.cancel(true);
            }

            if(text == null || text.isEmpty()) {
                task = new FluxTask(this);
                task.execute(page,session.getToken());
            }else{
                task = new RechercheTask(this);
                task.execute(text, page,session.getToken());
            }
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
        }
    }

    //Cree le whatwhat dans le cas ou le texte ne correspond a aucun
    private void creerWhatWhat(String text) {
        WhatWhat ww = new WhatWhat(text,session.getProfil());
        whatWhatList.clear();
        whatWhatList.add(ww);
        adapter.notifyDataSetChanged();
    }

    public void fermerClavier(){
        InputMethodManager imm = (InputMethodManager)getContext().getSystemService(
                Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
    }

    public Circle getCircle() {
        return circle;
    }

    public void setCircle(Circle circle) {
        this.circle = circle;
    }

    //---------------------RechercheTaskDelegate---------------------

    @Override
    public void afficherChargement(boolean afficher) {

    }

    @Override
    public void onFluxRecu(List<WhatWhat> whatWhatList) {
        this.whatWhatList.clear();
        this.whatWhatList.addAll(whatWhatList);
        adapter.notifyDataSetChanged();
        loadmore = true;
    }

    @Override
    public void onRechercheRecu(List<WhatWhat> whatWhatList) {
        this.whatWhatList.clear();
        this.whatWhatList.addAll(whatWhatList);
        adapter.notifyDataSetChanged();
        loadmore = true;
    }

    @Override
    public void onResultatVide() {
        loadmore = false;
        creerWhatWhat(text);
    }

    @Override
    public void onErreurReseau() {
        loadmore = false;
    }

    //---------------------FaireTaskDelegate---------------------

    @Override
    public void faire(WhatWhat whatWhat) {
        fermerClavier();
        if(circle != null)
            circle.close();
        if (whatWhat.isCree()) {
            faireWhatWhatTask = new FaireWhatWhatTask(this,false);
            faireWhatWhatTask.execute(whatWhat.getTexte(),session.getToken());
        } else {
            faireWhatWhatTask = new FaireWhatWhatTask(this,true);
            faireWhatWhatTask.execute(whatWhat,session.getToken());
        }
    }

    @Override
    public void onWhatWhatEnvoye(WhatWhat whatWhat) {
        Whatter profil = session.getProfil();
        profil.setWhatWhat(whatWhat);
        editText.setText("");
        Toast.makeText(getContext(),"WhatWhat envoyé",Toast.LENGTH_SHORT).show();
        faireWhatWhatTask = null;

        ((MainActivity)getContext()).notifyProfilChanged(profil,null);

    }

}
